package com.example.myfirstapp;

import groove.GrooveClient;
import groove.json.util.SearchResult;
import util.SearchResultAdapter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private GrooveClient client;
	private ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void doSearch(View view) {
		EditText text = (EditText) findViewById(R.id.edittext_query);
		
		if(client == null){
			Toast toast = Toast.makeText(this, "Client noch nicht geladen! Bitte gedulden Sie sich noch kurz!", Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			return;
		}
		
		String query = text.getText().toString();
		if(query == null || query.equals("")){
			Toast toast = Toast.makeText(this, "Bitte geben Sie einen Suchbegriff ein!", Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			return;
		}
		listView = (ListView) findViewById(R.id.listview_query);
		new GrooveClientQueryTask(this).execute(text.getText().toString());
			

		
	}

	@Override
	protected void onStart() {
		new GrooveClientCreationTask().execute();
		
		super.onStart();
	}

	private class GrooveClientCreationTask extends
			AsyncTask<Void, Void, GrooveClient> {

		@Override
		protected GrooveClient doInBackground(Void... params) {

			return new GrooveClient();
		}

		@Override
		protected void onPostExecute(GrooveClient result) {
			client = result;
		}
	}
	
	private class GrooveClientQueryTask extends
		AsyncTask<String, Void, SearchResult> {
		
		private Activity context;

		public GrooveClientQueryTask(Activity context){
			this.context = context;
		}
		
		@Override
		protected SearchResult doInBackground(String... params) {

			return client.getResultsFromSearch(params[0]);
		}

		@Override
		protected void onPostExecute(SearchResult result) {
			
			SearchResultAdapter adapter = new SearchResultAdapter(context, result, client);
			listView.setAdapter(adapter); 
			
		}
	}

}
